<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>大文件处理测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .log {
            background: #f5f5f5;
            padding: 10px;
            border-radius: 3px;
            font-family: monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 3px;
            background: #007bff;
            color: white;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        .progress {
            width: 100%;
            height: 20px;
            background: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }
        .progress-bar {
            height: 100%;
            background: #28a745;
            width: 0%;
            transition: width 0.3s;
        }
    </style>
</head>
<body>
    <h1>🧪 大文件处理策略测试</h1>
    
    <div class="test-section">
        <h3>内存检测</h3>
        <button onclick="testMemoryDetection()">检测可用内存</button>
        <div id="memoryResult" class="log"></div>
    </div>

    <div class="test-section">
        <h3>处理策略选择</h3>
        <button onclick="testStrategySelection()">测试策略选择</button>
        <div id="strategyResult" class="log"></div>
    </div>

    <div class="test-section">
        <h3>文件分析</h3>
        <input type="file" id="testFile" accept="video/*">
        <button onclick="testFileAnalysis()">分析文件</button>
        <div id="analysisResult" class="log"></div>
    </div>

    <div class="test-section">
        <h3>模拟处理进度</h3>
        <button onclick="testProgressSimulation()">模拟处理</button>
        <div class="progress">
            <div id="testProgress" class="progress-bar"></div>
        </div>
        <div id="progressResult" class="log"></div>
    </div>

    <script>
        // 创建测试用的优化器实例
        class TestVideoOptimizer {
            constructor() {
                this.maxMemoryUsage = 256 * 1024 * 1024;
                this.chunkSize = 64 * 1024 * 1024;
            }

            getAvailableMemory() {
                if ('memory' in performance) {
                    return performance.memory.jsHeapSizeLimit - performance.memory.usedJSHeapSize;
                }
                return this.maxMemoryUsage;
            }

            selectProcessingStrategy(fileSize, availableMemory) {
                const fileSizeGB = fileSize / (1024 * 1024 * 1024);
                const availableMemoryGB = availableMemory / (1024 * 1024 * 1024);

                if (fileSize < availableMemory * 0.3) {
                    return 'direct';
                } else if (fileSize < availableMemory * 0.8) {
                    return 'chunked';
                } else if (fileSizeGB < 2) {
                    return 'streaming';
                } else if (fileSizeGB < 5 && 'Worker' in window) {
                    return 'worker';
                } else {
                    return 'unsupported';
                }
            }

            formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            async analyzeFile(file) {
                const headerSize = Math.min(1024 * 1024, file.size);
                const header = await file.slice(0, headerSize).arrayBuffer();
                const headerView = new Uint8Array(header);
                
                return {
                    size: file.size,
                    type: file.type,
                    isMP4: this.checkMP4Format(headerView),
                    hasFastStart: this.checkFastStartFlag(headerView)
                };
            }

            checkMP4Format(headerView) {
                for (let i = 0; i < Math.min(headerView.length - 8, 1000); i++) {
                    if (headerView[i] === 0x66 && headerView[i+1] === 0x74 && 
                        headerView[i+2] === 0x79 && headerView[i+3] === 0x70) {
                        return true;
                    }
                }
                return false;
            }

            checkFastStartFlag(headerView) {
                for (let i = 0; i < Math.min(headerView.length - 8, 10000); i++) {
                    if (headerView[i] === 0x6D && headerView[i+1] === 0x6F && 
                        headerView[i+2] === 0x6F && headerView[i+3] === 0x76) {
                        return i < 1000;
                    }
                }
                return false;
            }
        }

        const testOptimizer = new TestVideoOptimizer();

        function testMemoryDetection() {
            const result = document.getElementById('memoryResult');
            const availableMemory = testOptimizer.getAvailableMemory();
            
            let output = `可用内存检测结果:\n`;
            output += `- 可用内存: ${testOptimizer.formatFileSize(availableMemory)}\n`;
            
            if ('memory' in performance) {
                const used = performance.memory.usedJSHeapSize;
                const total = performance.memory.totalJSHeapSize;
                const limit = performance.memory.jsHeapSizeLimit;
                
                output += `- 已使用: ${testOptimizer.formatFileSize(used)}\n`;
                output += `- 总分配: ${testOptimizer.formatFileSize(total)}\n`;
                output += `- 内存限制: ${testOptimizer.formatFileSize(limit)}\n`;
                output += `- 使用率: ${((used / limit) * 100).toFixed(1)}%\n`;
            } else {
                output += `- Performance Memory API 不可用\n`;
            }
            
            result.textContent = output;
        }

        function testStrategySelection() {
            const result = document.getElementById('strategyResult');
            const availableMemory = testOptimizer.getAvailableMemory();
            
            const testSizes = [
                50 * 1024 * 1024,      // 50MB
                200 * 1024 * 1024,     // 200MB
                500 * 1024 * 1024,     // 500MB
                1024 * 1024 * 1024,    // 1GB
                2 * 1024 * 1024 * 1024, // 2GB
                5 * 1024 * 1024 * 1024, // 5GB
                10 * 1024 * 1024 * 1024 // 10GB
            ];
            
            let output = `处理策略选择测试:\n`;
            output += `可用内存: ${testOptimizer.formatFileSize(availableMemory)}\n\n`;
            
            testSizes.forEach(size => {
                const strategy = testOptimizer.selectProcessingStrategy(size, availableMemory);
                output += `${testOptimizer.formatFileSize(size)} -> ${strategy}\n`;
            });
            
            result.textContent = output;
        }

        async function testFileAnalysis() {
            const fileInput = document.getElementById('testFile');
            const result = document.getElementById('analysisResult');
            
            if (!fileInput.files[0]) {
                result.textContent = '请先选择一个视频文件';
                return;
            }
            
            const file = fileInput.files[0];
            result.textContent = '正在分析文件...';
            
            try {
                const metadata = await testOptimizer.analyzeFile(file);
                
                let output = `文件分析结果:\n`;
                output += `- 文件名: ${file.name}\n`;
                output += `- 文件大小: ${testOptimizer.formatFileSize(metadata.size)}\n`;
                output += `- MIME类型: ${metadata.type}\n`;
                output += `- 是否MP4格式: ${metadata.isMP4 ? '是' : '否'}\n`;
                output += `- 是否已优化: ${metadata.hasFastStart ? '是' : '否'}\n`;
                
                const availableMemory = testOptimizer.getAvailableMemory();
                const strategy = testOptimizer.selectProcessingStrategy(file.size, availableMemory);
                output += `- 推荐策略: ${strategy}\n`;
                
                result.textContent = output;
            } catch (error) {
                result.textContent = `分析失败: ${error.message}`;
            }
        }

        function testProgressSimulation() {
            const progressBar = document.getElementById('testProgress');
            const result = document.getElementById('progressResult');
            
            let progress = 0;
            const phases = [
                { name: '分析文件结构', duration: 500 },
                { name: '检查文件格式', duration: 300 },
                { name: '准备处理环境', duration: 400 },
                { name: '智能处理策略', duration: 2000 },
                { name: '执行FFmpeg优化', duration: 1500 },
                { name: '验证处理结果', duration: 300 }
            ];
            
            let currentPhase = 0;
            let output = '模拟处理进度:\n';
            
            function updateProgress() {
                if (currentPhase >= phases.length) {
                    output += '✅ 处理完成!\n';
                    result.textContent = output;
                    progressBar.style.width = '100%';
                    return;
                }
                
                const phase = phases[currentPhase];
                output += `${new Date().toLocaleTimeString()} - ${phase.name}...\n`;
                result.textContent = output;
                
                progress = ((currentPhase + 1) / phases.length) * 100;
                progressBar.style.width = progress + '%';
                
                currentPhase++;
                setTimeout(updateProgress, phase.duration);
            }
            
            // 重置
            progress = 0;
            currentPhase = 0;
            output = '模拟处理进度:\n';
            progressBar.style.width = '0%';
            
            updateProgress();
        }

        // 页面加载时自动检测内存
        window.addEventListener('load', () => {
            testMemoryDetection();
            testStrategySelection();
        });
    </script>
</body>
</html>